package cn.slipi.admin.common.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;

/**
 * 图片工具类
 *
 * @author lee
 * @date 2018/3/27
 */
public class ImageUtil {
    private static final Logger LOG = LoggerFactory.getLogger(ImageUtil.class);

    /**
     * 根据byte数组，生成文件
     *
     * @param bytes
     * @param filePath
     *
     * @throws IOException
     */
    public static void writeFile(byte[] bytes, String filePath) throws IOException {
        BufferedOutputStream bos = null;
        FileOutputStream fos = null;
        File file = new File(filePath);
        if (!file.getParentFile().exists()) {
            file.getParentFile().mkdirs();
        }
        fos = new FileOutputStream(file);
        bos = new BufferedOutputStream(fos);
        bos.write(bytes);
        bos.close();
        fos.close();
    }

    public static byte[] readFile(String filePath) throws IOException {
        byte[] data = new byte[0];
        try {
            InputStream inputStream = null;
            data = null;
            inputStream = new FileInputStream(filePath);
            data = new byte[inputStream.available()];
            inputStream.read(data);
            inputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return data;
    }


    public static byte[] convertBase64ToByte(String base64Str) {
        if (!StringUtils.isEmpty(base64Str)) {
            BASE64Decoder decoder = new BASE64Decoder();
            byte[] b = new byte[0];
            try {
                b = decoder.decodeBuffer(base64Str);
                for (int i = 0; i < b.length; ++i) {
                    if (b[i] < 0) {
                        b[i] += 256;
                    }
                }
                return b;
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    public static String convertByteToBase64(byte[] bytes) {
        if (bytes != null) {
            BASE64Encoder encoder = new BASE64Encoder();
            return encoder.encode(bytes);
        }
        return null;
    }

    public static void writeImage(String text, OutputStream os) throws IOException {
        // 图像buffer
        BufferedImage buffImg = new BufferedImage(180, 230, BufferedImage.TYPE_INT_RGB);
        Graphics2D g = buffImg.createGraphics();
        // 将图像填充为白色
        g.setColor(Color.black);
        g.fillRect(0, 0, 180, 230);
        g.setColor(new Color(255, 255, 255));
        g.drawString(text, 76, 100);
        ImageIO.write(buffImg, "png", os);
        os.close();
    }

}